#include "DeviceTime.h"
#include <pthread.h>
#include "Log.h"
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/system_properties.h>


int carplaySessionConnectedDeviceTime = 0;
pthread_t 		m_DeviceTimeTid;
pthread_t *		m_DeviceTimeTidPtr;

void (*pRequestSendDeviceTime)( );
volatile int keepDeviceTimeRunning = 1;

void *deviceTimeThread(void *arg) {
	keepDeviceTimeRunning = 1;
	char osTime [20] = { 0 };
	long udcTime = 1704443721;
	__system_property_get("ro.system.build.date.utc", osTime);
	if(strlen(osTime) > 0)
	{
		udcTime = atol( osTime );
		udcTime += 120;
		if(udcTime < 1704443721)
		{
			udcTime = 1704443721;
		}

	}
	while ( keepDeviceTimeRunning ){

		if( carplaySessionConnectedDeviceTime == 1)
		{
			uint64_t nanos;
			struct timespec ts;

			ts.tv_sec = 0;
			ts.tv_nsec = 0;
			clock_gettime(CLOCK_REALTIME, &ts);
			nanos = ts.tv_sec;
			nanos *= 1000000000;
			nanos += ts.tv_nsec;

			LOGD("observe device time ts.tv_sec = %llu \n", ts.tv_sec);

			uint64_t referenceData = nanos / 1000000000;
			LOGD("observe device time referenceData = %llu \n", referenceData);
		    if( referenceData > udcTime )
		    {

				if( pRequestSendDeviceTime != NULL )
				{
					pRequestSendDeviceTime();
				}
				keepDeviceTimeRunning = 0;
				break;
		    }

		}
		usleep(1000*1000);
	}

	return (NULL);
}

void RegisterSendDeviceTimeUpdate(void (*pFunc)())
{
	pRequestSendDeviceTime = pFunc;
	int ret;
	if ((ret = pthread_create(&m_DeviceTimeTid, NULL, deviceTimeThread, NULL))
			!= 0) {
		LOGD("observe device time thread create failed!\n");
	} else {
		m_DeviceTimeTidPtr = &m_DeviceTimeTid;
		LOGD("observe device time thread create successed!\n");
	}
}

void DeviceTimeOnCarPlaySessionConnected( )
{
	carplaySessionConnectedDeviceTime = 1;
}


void DeviceTimeOnCarPlaySessionDisconnected( )
{
	carplaySessionConnectedDeviceTime = 0;
}




